package au.com.bus4u.utils;


import au.com.bus4u.Bus4uApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

@Component
@Scope("prototype")//对象注解Scope是多例的。
public class DynamicTask {

    private String cron;
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;//注入线程池任务调度程序
    private ScheduledFuture future;
    private String threadName;
    public void startCron(String threadName,Runnable runnable,CronTrigger cronTrigger) {
        this.threadName=threadName;
        int poolSize = threadPoolTaskScheduler.getPoolSize();
//        System.err.println("poolSize = " + poolSize);
//        System.err.println(threadName+":start");
        //第一个参数Runnable  线程任务       第二个参数CronTrigger 触发器
        future = threadPoolTaskScheduler.schedule(runnable, cronTrigger);
        Bus4uApplication.map.put(threadName, future);
//        System.err.println(threadName+":end");
    }

    public void startCron() {
        cron = "0/1 * * * * ?";
//        System.err.println(Thread.currentThread().getName()+":start");
        String name = Thread.currentThread().getName();

        //第一个参数Runnable  线程任务
        //第二个参数CronTrigger 触发器
        future = threadPoolTaskScheduler.schedule(new myTask(name), new CronTrigger(cron));
        Bus4uApplication.map.put(name, future);
//        System.err.println(Thread.currentThread().getName()+":end");
    }

    public void stop() {
//        System.err.println("线程任务:"+threadName+" , 被关闭了!");
//        System.err.println("定时任务关闭时间:" + DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
        if (future != null) {
            future.cancel(true);
        }
    }

    private class myTask implements Runnable {
        private String name;

        myTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
//            System.err.println("线程任务:" + name+" ，被执行了");
        }
    }

}
